<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/5/25 0025
 * Time: 19:12
 */
namespace Api\Service;

class WechatService extends \We
{
    /**
     * 获取微信支付配置
     * @param array|null $options 参数
     * @return array
     */
    public static function config($options = null)
    {
        /* 读取数据库中的配置 */
        $config =   S('DB_CONFIG_DATA');
        if(!$config){
            $config =   api('Config/lists');
        }
        if (empty($options)) $options = [
            // 微信功能必需参数
            'appid'          => $config['WECHAT_APPID'],
            'appsecret'      => $config['WECHAT_APPSECRET'],
            // 微信支付必要参数
            'mch_id'         => $config['WECHAT_MCH_ID'],
            'mch_key'        => $config['WECHAT_KEY'],
            'cache_path'     => RUNTIME_PATH . 'wechat' . DIRECTORY_SEPARATOR,
        ];
        return parent::config($options);
    }


    /**
     * 静态魔术加载方法
     * @param string $name 静态类名
     * @param array $arguments 参数集合
     * @return mixed
     * @throws \think\Exception
     */
    public static function __callStatic($name, $arguments)
    {
        $config = [];
        if (is_array($arguments) && count($arguments) > 0) {
            $option = array_shift($arguments);
            $config = is_array($option) ? $option : self::config();
        }
        if (in_array($name, ['wechat'])) {
            return self::instance(trim($name, '_'), 'WeChat', $config);
        } elseif (substr($name, 0, 6) === 'WeChat') {
            return self::instance(substr($name, 6), 'WeChat', $config);
        } elseif (substr($name, 0, 6) === 'WeMini') {
            return self::instance(substr($name, 6), 'WeMini', $config);
        } elseif (substr($name, 0, 5) === 'WePay') {
            return self::instance(substr($name, 5), 'WePay', $config);
        } elseif (substr($name, 0, 6) === 'AliPay') {
            return self::instance(substr($name, 6), 'AliPay', $config);
        } else {
            throw new \think\Exception("class {$name} not found");
        }
    }

    /**
     * 接口对象实例化
     * @param string $name 接口名称
     * @param string $type 接口类型
     * @param array $config 微信配置
     * @return mixed
     * @throws \think\Exception
     */
    public static function instance($name, $type = 'WeChat', $config = [])
    {
        if (class_exists($class = "\\{$type}\\" . ucfirst(strtolower($name)))) {
            return new $class(empty($config) ? self::config() : $config);
        } else {
            throw new \think\Exception("Class {$class} not found");
        }
    }
}